import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Modal,
  Divider, message,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import ConfirmComponent from '@/common/confirmComponent';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescView from './descView';
import styles from '../UserManage.less';
import * as options from '../../../common/options';
import { powerBtnFunc } from '@/utils/utils';

const Option = Select.Option;
const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ repayment, loading }) => ({
  repayment,
  loading: loading.models.repayment,
}))

@Form.create()
class repayment extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      configModalVisible: false,
      lookDescView: false,
      selectedRows: {},
      formValues: {},
      pagination: {
        pageNo: 1,
        pageSize: 15,
      },
    };
  }

  componentDidMount() {
    this.getList();
  }

  columns = [
    {
      title: '还款编号',
      dataIndex: 'repaymentNo',
      key: 'repaymentNo',
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
    },
    {
      title: '企业名称',
      dataIndex: 'enterpriseName',
      key: 'enterpriseName',
    },
    {
      title: '还款方式',
      dataIndex: 'repayMode',
      key: 'repayMode',
      render: val => <span>{options.repayMode.map(item => (item.key === val ? item.value : ''))}</span>,
    },

    {
      title: '本金',
      dataIndex: 'principal',
      key: 'principal',
    },
    {
      title: '利息',
      dataIndex: 'interest',
      key: 'interest',
    },
    {
      title: '服务费',
      dataIndex: 'fee',
      key: 'fee',
    },
    {
      title: '还款时间',
      dataIndex: 'repayTime',
      key: 'repayTime',
    },
    {
      title: '回款时间',
      key: 'backTime',
      dataIndex: 'backTime',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: val => <span>{options.repayStatus.map(item => (item.key === val ? item.value : ''))}</span>,
    },
    {
      title: '操作',
      key: 'dataIndex',
      render: (text, record) => (
        <Fragment>
          {
            powerBtnFunc('100100', [
              <a key={'config'}
                 disabled={record.status !== 1}
                 onClick={() => this.handleConfigModalVisible(true, record)}>还款确认</a>,
              <Divider key={'divider'} type="vertical"/>])}
          {
            powerBtnFunc('100099',
              < a key={'view'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
            )}
        </Fragment>
      ),
    },
  ];
  getList = () => {
    const { pagination } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'repayment/fetch',
      payload: pagination,
    });
  };

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };

    dispatch({
      type: 'repayment/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'repayment/fetch',
      payload: {},
    });
  };

  //搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'repayment/fetch',
        payload: values,
      });
    });
  };
  //确认
  handleConfigModalVisible = (flag, record) => {
    this.setState({
      configModalVisible: flag,
      selectedRows: record,
    });
  };
  //确认请求
  handleConfigOk = (fileList) => {
    let _this = this;
    const { selectedRows } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'repayment/confirm',
      payload: { repaymentNo: selectedRows.repaymentNo, voucher: fileList[0].url },
      callback(response) {
        if (response.code === 200) {
          _this.handleConfigModalVisible(false, []);
          _this.getList();
          message.success('还款成功');
        } else {
          message.error(response.errMsg);
        }
      },
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    const { dispatch } = this.props;
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'repayment/detail',
          payload: { code: record.repaymentNo },
        });
      }
    });

  };


  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="企业编号">
              {getFieldDecorator('enterpriseNo')(<Input placeholder="请输入企业编号"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('enterpriseName')(<Input placeholder="请输入企业名称"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {options.loanStatus.map((item) => {
                    return <Option value={item.key} key={item.key}>{item.value}</Option>;
                  })}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
          <span className={styles.submitButtons}>
          <Button type="primary" htmlType="submit">
          查询
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
          重置
          </Button>

          </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { repayment: { data, details }, loading } = this.props;
    const { selectedRows, lookDescView, configModalVisible } = this.state;
    return (
      <PageHeaderWrapper title="还款管理">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>

            {data ?
              <StandardTable
                selectedRows={selectedRows}
                loading={loading}
                data={data}
                rowKey={'repaymentNo'}
                rowSelectHide={true}
                columns={this.columns}
                onChange={this.handleStandardTableChange}
              /> : ''}
          </div>
        </Card>
        {details ?
          <DescView handleLookDesc={this.handleLookDesc} selectedRows={details} lookDescView={lookDescView}/>
          : ''
        }
        <ConfirmComponent
          handleVisible={this.handleConfigModalVisible}
          configVisible={configModalVisible}
          onOk={this.handleConfigOk}/>
      </PageHeaderWrapper>
    );
  }
}

export default repayment;
